﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

/// <summary>
/// Summary description for ChatMessageDA
/// </summary>
public class ChatMessageDA
{
	public ChatMessageDA()
	{
		
	}

    public int Send(ChatMessage msg)
    {
        string command = "sp_tb_chatroom_messages_SendMessage";
        SqlConnection sqlCon = new SqlConnection(DatabaseFunctions.GetConnectionString());
        SqlCommand sqlCmd = new SqlCommand(command, sqlCon);
        sqlCon.Open();
        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;

        sqlCmd.Parameters.Add(new SqlParameter("@userID", SqlDbType.NVarChar, 255, ""));
        sqlCmd.Parameters.Add(new SqlParameter("@roomID", SqlDbType.NVarChar, 255, ""));
        sqlCmd.Parameters.Add(new SqlParameter("@text", SqlDbType.NText));
        sqlCmd.Parameters.Add(new SqlParameter("@result", SqlDbType.Int, 32, ""));
        sqlCmd.Parameters["@result"].Direction = ParameterDirection.Output;

        sqlCmd.Parameters["@userID"].Value = msg.SenderID;
        sqlCmd.Parameters["@roomID"].Value = msg.RoomID;
        sqlCmd.Parameters["@text"].Value = msg.Text;

        sqlCmd.ExecuteNonQuery();

        int result = 0;

        try
        {
            result = Convert.ToInt16(sqlCmd.Parameters["@result"].Value);
        }
        catch (Exception ex)
        {
            result = 0;
        }

        sqlCon.Close();

        return result;
    }

    public DataTable Read(ChatRoom room)
    {
        string command = "sp_tb_chatroom_messages_ReadMessages @roomID='" + room.ID + "'";
        SqlConnection sqlCon = new SqlConnection(DatabaseFunctions.GetConnectionString());
        sqlCon.Open();
        SqlDataAdapter sda = new SqlDataAdapter(command, sqlCon);

        DataTable dsReminders = new DataTable();
        sda.Fill(dsReminders);
        
        sqlCon.Close();
        return dsReminders;
    }  
}
